<?php
class UserAction extends BaseAction {
    /**
     * 注册
     */
    public function register(){
        if($this->isPost()){
            $email = $this->_post('email');
            $mobile = $this->_post('mobile');
            $password = $this->_post('password');
            $re_password = $this->_post('re_password');
            $code = $this->_post('code');
            $user_type = $this->_post('user_type');
            $auth_code = $this->_post('auth_code');
            $this->check_empty($email,'邮箱账号不能为空');
            $this->check_empty($mobile,'手机号不能为空');
            $this->check_empty($password,'密码不能为空');
            $this->check_empty($re_password,'确认密码不能为空');
            $this->check_empty($code,'验证码不能为空');
            $this->check_empty($auth_code,'短信验证码不能为空');
            $this->check_empty($user_type,'用户类型不能为空');
            if(!$this->checkEmail($email)){
                $this->return_status('0' ,"邮箱账号格式错误");
            }
            $session_code = session('verify');
            $code = md5(strtoupper($code));
            if($session_code != $code){
                session('verify',null);
                $this->return_status('0' ,"验证码输入不正确");
            }else{
                session('verify',null);
            }
            $session_auth_code = session('register_code');
            if($auth_code != $session_auth_code){
                session('register_code',null);
                $this->return_status('0' ,'短信验证码输入不正确,已失效');
            }else{
                session('register_code',null);
            }
            if(strlen($password) < 6){
                $this->return_status('0' ,'密码不能少于6位数');
            }
            if(strlen($password) > 16){
                $this->return_status('0' ,'密码不能超过16位');
            }
            if($password != $re_password){
                $this->return_status('0' ,'密码输入不一致');
            }else{
                $password = md5($password);
            }
            $condition = array();
            $condition['email'] = $email;
            $row = M('user')->where($condition)->find();
            if(isset($row['id'])){
                $this->return_status('0' ,'邮箱已经存在');
            }else{
                $data = array();
                $data['email'] = $email;
                $data['user_name'] = $email;
                $data['mobile'] = $mobile;
                $data['user_pwd'] = $password;
                $data['user_type'] = strval($user_type);
                $data['create_time'] = TIME_NOW;
                $data['update_time'] = TIME_NOW;
                $data['is_effect'] = '1';
                $data['avatar'] = '/avatar/noavatar.gif';
                $uid = M('user')->data($data)->add();
                //$sql = M('user')->_sql();
                if($uid){
                    session('uid',$uid);
                    session('mobile',$mobile);
                    session('username',$email);
                    session('email',$email);
                    session('avatar',$data['avatar']);
                    send_welcome_mail($uid,$email,$email);
                    $sync_data = array('email'=>$email,'password'=>$re_password,'mobile'=>$mobile);
                    sync_data($sync_data);
                    $this->return_status('1' ,'注册成功');
                }else{
                    $this->return_status('0' ,'注册失败,请联系客服');
                }
            }

        }else{
            $this->error("数据提交不正确");
        }
    }


    /**
     * 登陆
     */
    public function login(){
        if($this->isPost()){
            $username = $this->_post('username');
            $password = $this->_post('password');
            $code = $this->_post('code');
            if(empty($username)){
                $this->return_status('0' ,'邮箱不能为空');
            }
            if(empty($password)){
                $this->return_status('0' ,'密码不能为空');
            }
            if(strlen($password) < 6){
                $this->return_status('0' ,'密码不能小于6位');
            }
            if(strlen($password) > 16){
                $this->return_status('0' ,'密码不能超过16位');
            }
            if(empty($code)){
                $this->return_status('0' ,'验证码不能为空');
            }else{
                $session_code = session('verify');
                $code = md5(strtoupper($code));
                if(empty($session_code) || $session_code != $code){
                    $this->return_status('0' ,'验证码输入不正确');
                }
            }

            $condition = array();
            //$where = array();
            //$where['email'] = $username;
            //$where['user_name'] = $username;
            //$where['mobile'] = $username;
            //$where['_logic'] = 'OR';
            //$condition['_complex'] = $where;
            $condition['email'] = $username;
            $condition['user_pwd'] = md5($password);
            $row = M('user')->where($condition)->find();
            $url = session('redirect_url') ? session('redirect_url') : '/';
            if($url != '/'){
                $url_data = parse_url($url);
                $query = parse_str($url_data['query']);
                if(isset($query['request_login'])){
                    unset($query['request_login']);
                }
                if(empty($query)){
                    $url = $url_data['path'];
                }else{
                    $url = $url_data['path'].http_build_query($query);
                }
            }
            if(isset($row['id'])){
                if(empty($row['mobile'])){
                    $this->return_status('2','您需要绑定手机号才能登陆');
                }
                if($row['is_effect'] == '0'){
                    $this->return_status('2','您的账号已被禁用，如有疑问请联系管理员');
                }
                session('uid',$row['id']);
                session('mobile',$row['mobile']);
                session('username',$username);//fix it
                session('email',$row['email']);
                session('avatar',$row['avatar']);
                session('redirect_url',null);
                $sync_data = array('username'=>$username,'password'=>$password,'mobile'=>$row['mobile']);
                sync_data($sync_data);
                $result = array('status'=>'1','info'=>'登陆成功','url'=>$url);
                exit(json_encode($result,JSON_HEX_TAG));
            }else{
                $this->return_status('0' ,'账号或者密码错误');
            }
        }else{
            $this->error("数据提交不正确");
        }
    }

    /**
     * 退出
     */
    public function logout(){
        session(null);
        $this->redirect('/');
    }

    public function sms_validator(){
        $type = strtolower(trim($this->_request('type')));
        $type_list = array('bind' , 'new' , 'old');

        if(!in_array($type,$type_list)){
            $this->return_status('0' ,'非法请求');
        }

        if($type != 'bind'){
            $this->require_login();
        }
        $mobile = $this->_request('mobile');
        if(empty($mobile) || !is_numeric($mobile) || strlen($mobile) != 11){
            $this->return_status('0' ,'请输入正确的手机号');
        }

        if($type == 'old'){
            $old_mobile = M('user')->where(array('mobile'=>$mobile))->getField('mobile');
            if(empty($old_mobile) || $old_mobile != $mobile){
                $this->return_status('0' ,'您输入的旧手机号不正确');
            }
        }
//        else{
//            $uid = M('user')->where(array('mobile'=>$mobile))->getField('id');
//            if(!empty($uid) && $uid != $this->uid){
//                $this->return_status('0' ,'您的手机号已被使用');
//            }
//        }
        import('ORG.Util.String');
        $code = String::randString(6, 1);
        session('user_mobile_auth_code_'.$type,$code);
        $project_send_time = session('project_send_time'.$type);
        if(empty($project_send_time)){
            session('project_send_time'.$type,TIME_NOW);
        }else{
            if(TIME_NOW - $project_send_time <= 60){
                $this->return_status('0' ,'发送频率不能少于60秒,请稍后再试');
            }else{
                session('project_send_time'.$type,null);
            }
        }
        $template  = M('msg_template')->where(array('name'=>'TPL_USER_MOBILE_AUTHCODE'))->getField('content');
        if(empty($template)){
            $this->return_status('0' ,'发送类型不存在,请检查');
        }else{
            $template = str_replace('{$code}',$code,$template);
        }
        require_once SITE_PATH."system/utils/es_sms.php";
        $sms = new sms_sender();

        $result = $sms->sendSms($mobile,$template);
        if($result['status'])
        {
            $this->return_status('1' ,'发送成功 , 手机验证码:');
        }
        else
        {
            $this->return_status('0' ,'发送失败');
        }
    }

    public function sms_valid(){
        $mobile = $this->_request('mobile');
        if(empty($mobile) || !is_numeric($mobile) || strlen($mobile) != 11){
            $this->return_status('0' ,'请输入正确的手机号');
        }
//        $where = array();
//        $where['mobile'] = $mobile;
//        $where['user_name'] = $mobile;
//        $where['_logic'] = 'OR';
//        if(M('user')->where($where)->find()){
//            $this->return_status('0' ,'您的手机号已被注册');
//        }
        import('ORG.Util.String');
        $code = String::randString(6, 1);
        session('register_code',$code);
        $send_time_valid = session('register_send_time');
        if(empty($send_time_valid)){
            session('register_send_time',TIME_NOW);
        }else{
            if(TIME_NOW - $send_time_valid <= 60){
                $this->return_status('0' ,'发送频率不能少于60秒,请稍后再试');
            }else{
                session('register_send_time',null);
            }
        }
        $template  = M('msg_template')->where(array('name'=>'TPL_REGISTER_USER_AUTHCODE'))->getField('content');
        if(empty($template)){
            $this->return_status('0' ,'发送类型不存在');
        }else{
            $template = str_replace('{$code}',$code,$template);
        }
        require_once SITE_PATH."system/utils/es_sms.php";
        $sms = new sms_sender();

        $result = $sms->sendSms($mobile,$template);
        if($result['status'])
        {
            $this->return_status('1' ,'发送成功');
        }
        else
        {
            $this->return_status('0' ,'发送失败');
        }
    }

    /**
     * 会员中心/我发起的项目
     */
    public function index(){
        $this->require_login();
        $condition = array();
        $condition['user_id'] = $this->uid;
        $type = $this->_get('type');
        if($type != ''){
            if($type == '0'){
                //众筹失败
                $condition['end_time'] = array(array('LT',TIME_NOW),array('NEQ','0'),'AND');
                $condition['is_success'] = '0';
            }
            if($type == '1') {
                $condition['is_success'] = '1';
                $condition['end_time'] = array(array('LT',TIME_NOW),array('NEQ','0'),'AND');
            }
            if($type == '2')
            {
                $condition['end_time'] = array(array('GT',TIME_NOW),array('NEQ','0'),'AND');
            }
        }
        $fav_total = M('deal_fav')->where(array('user_id'=>$this->uid))->count();
        $support_total = M('deal_order')->where(array('user_id'=>$this->uid))->count();
        $post_total = M('deal')->where(array('user_id'=>$this->uid))->count();
        $this->assign(array('fav_total'=>intval($fav_total),'support_total'=>intval($support_total),'post_total'=>intval($post_total)));
        $post_total = M('deal')->where($condition)->count();
        $Page = new Page($post_total,10,array('type'=>$type));
        $this->assign('page',$Page->show_front());
        $this->assign("current_page",$Page->nowPage);
        $list = M('deal')->where($condition)->limit($Page->firstRow,$Page->listRows)->order('id desc')->select();
        $ids="0,";$return =array();
        foreach($list as $k=>$v)
        {
            $ids .= $v['id'].",";
            $v['reply_comments'] = 0;//初始化未回复数
            $return[$v['id']] = $this->deal_info_format($v);
            $deal_item_images = M('deal_item_image')->where(array('deal_id'=>$v['id']))->find();
            $return[$v['id']]['deal_item_images'] = $deal_item_images['image']?$deal_item_images['image']:"/images/home/default_payback-pic100x100.jpg";
        }
        $ids=trim($ids,",");
        $condition=array();
        $condition['reply_status']='0';
        $condition['deal_id']=["in",$ids];
        $comment_list=M('deal_comment')->where($condition)->field('deal_id,COUNT(*) AS num')->select();
        if($comment_list){
            foreach($comment_list as $k=>$v){
                if($v['num']>0){
                    $return[$v['deal_id']]['reply_comments']=$v['num'];
                }
            }
        }
        $list=array_values($return);
        $this->assign('type',$type);
        $this->assign('list',$list);
        $this->display();
    }

    /**
     * 我喜欢的项目
     */
    public function favorite(){
        $this->require_login();
        $fav_total = M('deal_fav')->where(array('user_id'=>$this->uid))->count();
        $support_total = M('deal_order')->where(array('user_id'=>$this->uid))->count();
        $post_total = M('deal')->where(array('user_id'=>$this->uid))->count();
        $this->assign(array('fav_total'=>intval($fav_total),'support_total'=>intval($support_total),'post_total'=>intval($post_total)));
        $Page = new Page($fav_total,10);
        $this->assign('page',$Page->show_front());
        $this->assign("current_page",$Page->nowPage);
        $fav_list = M('deal_fav')->alias('fav')->join('__DEAL__ deal on fav.deal_id = deal.id')->where(array('fav.user_id'=>$this->uid))->field('deal.*,fav.id as fav_id')->limit($Page->firstRow,$Page->listRows)->select();
        foreach($fav_list as $k=>$v)
        {
            $fav_list[$k] = $this->deal_info_format($v);
            $deal_item_images = M('deal_item_image')->where(array('deal_id'=>$v['id']))->find();
            $fav_list[$k]['deal_item_images'] = $deal_item_images['image']?$deal_item_images['image']:"/images/home/default_payback-pic100x100.jpg";
        }
        $this->assign('list',$fav_list);
        $this->display();
    }


    /**
     * 个人设置
     */
    public function profile(){
        $this->require_login();
        if($this->isPOST()){
            $where = array('id'=>$this->uid);
            $old_data = M('user')->where($where)->find();
            $data = array();
            if(empty($old_data['ex_real_name'])){
                $data['ex_real_name'] = strim($_REQUEST['realname']);//真实姓名
                $this->check_empty($data['ex_real_name'],'真实姓名不能为空');
            }
            $data['province'] = strim($_REQUEST['province']);//省份
            $data['city'] = strim($_REQUEST['city']);//城市
            if($old_data['user_type'] == ''){
                $this->check_empty($_REQUEST['user_type'],'用户类型不能为空，选择后不能变更');
                $data['user_type'] = intval($_REQUEST['user_type']) == '0' ? '0' : '1';//用户类型 0:个人 1:企业 默认个人
            }
            $data['sex'] = intval($_REQUEST['sex']);//性别
            $data['ex_bank_name'] = strim($_REQUEST['ex_bank_name']);//银行名称
            $data['ex_bank_branch'] = strim($_REQUEST['ex_bank_branch']);//开户支行
            $data['ex_bank_author'] = $data['ex_real_name']?$data['ex_real_name']:$old_data['ex_real_name'];//开户名称
            $data['ex_account_info'] = strim($_REQUEST['ex_account_info']);//银行账号
            $data['intro'] = strim($_REQUEST['intro']);//自我介绍

            $this->check_empty($data['sex'],'请选择性别');
            $this->check_empty($data['province'],'所在地省份不能为空');
            $this->check_empty($data['city'],'所在地城市不能为空');
            $this->check_empty($data['intro'],'自我介绍不能为空');
            $this->check_empty($data['ex_bank_name'],'银行名称不能为空');
            $this->check_empty($data['ex_bank_branch'],'开户支行不能为空');
            $this->check_empty($data['ex_bank_author'],'开户名称不能为空');
            $this->check_empty($data['ex_account_info'],'银行账号不能为空');

            if(msubstr($data['intro'],0,500) != $data['intro']){
                $this->return_status('0','自我介绍不能超过500个字');
            }
            $session_code = session('verify');
            $code = md5(strtoupper($this->_post('code')));
            if($session_code != $code){
                session('verify',null);
                $this->return_status('0','验证码输入不正确');
            }else{
                session('verify',null);
            }
            $status = M('user')->where($where)->data($data)->save();
            if($status){
                $sync_data = array('email'=>$old_data['email'],'mobile'=>$old_data['mobile']);
                if(empty($old_data['ex_real_name'])){
                    $sync_data['ex_real_name'] = strim($_REQUEST['realname']);//真实姓名
                }else{
                    $sync_data['ex_real_name'] = $old_data['ex_real_name'];
                }
                $sync_data['province'] = $data['province'];//省份
                $sync_data['city'] = $data['city'];//城市
                sync_data($sync_data);
                $this->return_status('1','资料更新成功');
            }else{
                $this->return_status('0','资料没有任何变更');
            }

        }else{
            $identity_filename = '/attachment/identity/'.md5($this->uid.$this->email).'.png';
            $this->assign('identity_filename',$identity_filename);
            $this->display();
        }
    }

    /**
     * 发货设置
     */
    public function express(){
        $this->require_login();
        if($this->isPOST()){

            $order_id = $_REQUEST['order_id'];
            $row = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->field('a.*,b.user_id as project_user_id')->where(array('a.id'=>$order_id,'a.order_status'=>'3','a.is_refund'=>'0','b.is_success'=>'1'))->find();
            if($row){
                if($row['project_user_id'] != $this->uid){
                    $this->return_status('0','您不是项目发起人,不能进行发货');
                }
                if($row['order_status'] != '3'){
                    $this->return_status('0','订单状态异常,不能发货');
                }
                if($row['express_status'] == '1'){
                    //重新发货,不做处理7

                }
                $data = array();
                $data['express_status'] = '1';
                $data['express_name'] = $_REQUEST['express_name'];
                $data['express_code'] = $_REQUEST['express_code'];
                $data['express_sn'] = $_REQUEST['express_sn'];
                $data['is_success'] = '1';
                $this->check_empty($data['express_name'],'快递公司不能为空');
                $this->check_empty($data['express_code'],'快递公司代码不能为空');
                $this->check_empty($data['express_sn'],'快递单号不能为空');
                $status = M('deal_order')->where(array('id'=>$order_id,'order_status'=>'3','is_refund'=>'0'))->data($data)->save();
                if($status){
                    $mobile = M('user')->where(array('id'=>$row['user_id']))->limit(1)->getField('mobile');
                    if(!empty($mobile)){
                        $sms_data = array('user_name'=>$row['user_name'],'project'=>$row['deal_name'],'express_sn'=>$data['express_sn'],'express_company'=>$data['express_name']);
                        $this->send_sms('TPL_USER_EXPRESS_MESSAGE',$mobile,$sms_data);
                        $this->return_status('1','发货成功,消息已经通知到客户');
                    } else{
                        $this->return_status('1','发货成功,客户没有设置手机');
                    }
                }else{
                    $this->return_status('0','发货失败,请联系客服');
                }
            }else{
                $this->return_status('0','找不到该订单信息');
            }
        }else{
            $type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : 'all';
            $deal_id = intval($_REQUEST['deal_id']) ? trim($_REQUEST['deal_id']) : '';
            $deal_list = M('deal')->where(array('is_success'=>'1','end_time'=>array(array('LT',TIME_NOW),array('NEQ','0'),'AND'),'user_id'=>$this->uid))->field('id,name')->select();
            $deal_title = '全部产品';
            if(!empty($deal_id)){
                $deal_title_rs = M('deal')->where(array('is_success'=>'1','user_id'=>$this->uid,'id'=>$deal_id))->limit(1)->getField('name');
                if(isset($deal_title_rs)){
                    $deal_title = $deal_title_rs;
                }
            }
            switch($type){
                case 'unship':
                    $condition = array('b.user_id'=>$this->uid,'a.order_status'=>'3','a.is_refund'=>'0','a.express_status'=>'0','c.is_delivery'=>'1','b.is_success'=>'1');
                    $condition['b.end_time'] = array(array('LT',TIME_NOW),array('NEQ','0'),'AND');
                    if(!empty($deal_id)){
                        $condition['a.deal_id'] = $deal_id;
                    }
                    $total = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->where($condition)->count();
                    $Page = new Page($total,10,array('type'=>$type));
                    $this->assign('page',$Page->show_front());
                    $this->assign("current_page",$Page->nowPage);
                    $list = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->field('a.*,b.name as project_name,b.image as project_image,c.title as item_title,c.is_delivery')->where($condition)->limit($Page->firstRow,$Page->listRows)->select();
                    break;
                case 'ship':
                    $condition = array('b.user_id'=>$this->uid,'a.order_status'=>'3','a.is_refund'=>'0','a.express_status'=>'1','c.is_delivery'=>'1','b.is_success'=>'1');
                    $condition['b.end_time'] = array(array('LT',TIME_NOW),array('NEQ','0'),'AND');
                    if(!empty($deal_id)){
                        $condition['a.deal_id'] = $deal_id;
                    }
                    $total = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->where($condition)->count();
                    $Page = new Page($total,10,array('type'=>$type));
                    $this->assign('page',$Page->show_front());
                    $this->assign("current_page",$Page->nowPage);
                    $list = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->field('a.*,b.name as project_name,b.image as project_image,c.title as item_title,c.is_delivery')->where($condition)->limit($Page->firstRow,$Page->listRows)->select();
                    break;
                case 'not_ship':
                    $condition = array('b.user_id'=>$this->uid,'a.order_status'=>'3','a.is_refund'=>'0','c.is_delivery'=>'0','b.is_success'=>'1');
                    $condition['b.end_time'] = array(array('LT',TIME_NOW),array('NEQ','0'),'AND');
                    if(!empty($deal_id)){
                        $condition['a.deal_id'] = $deal_id;
                    }
                    $total = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->where($condition)->count();
                    $Page = new Page($total,10,array('type'=>$type));
                    $this->assign('page',$Page->show_front());
                    $this->assign("current_page",$Page->nowPage);
                    $list = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->field('a.*,b.name as project_name,b.image as project_image,c.title as item_title,c.is_delivery')->where($condition)->limit($Page->firstRow,$Page->listRows)->select();
                    break;
                default:
                    $condition = array('b.user_id'=>$this->uid,'a.order_status'=>'3','a.is_refund'=>'0','b.is_success'=>'1');
                    $condition['b.end_time'] = array(array('LT',TIME_NOW),array('NEQ','0'),'AND');
                    if(!empty($deal_id)){
                        $condition['a.deal_id'] = $deal_id;
                    }
                    $total = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->where($condition)->count();
                    $Page = new Page($total,10,array('type'=>$type));
                    $this->assign('page',$Page->show_front());
                    $this->assign("current_page",$Page->nowPage);
                    $list = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->field('a.*,b.name as project_name,b.image as project_image,c.title as item_title,c.is_delivery')->where($condition)->limit($Page->firstRow,$Page->listRows)->select();
                    break;
            }
            $this->assign('type',$type);
            $this->assign('deal_id',$deal_id);
            $this->assign('deal_list',$deal_list);
            $this->assign('list',$list);
            $this->assign('deal_title',$deal_title);
            $this->display();
        }
    }

    /**
     * 头像修改页
     */
    public function avatar(){
        $this->require_login();
        if($this->isPOST()){
            $uid_array = str_split($this->uid);
            $uid_path = implode('/',$uid_array).'/';
            $path = WEB_PATH.'avatar/'.$uid_path;
            $web_path = '/avatar/'.$uid_path.$this->uid.'.png';
            $info = webuploader('name',$path,$web_path,$this->uid.'.png');
            $source_file = $path . $this->uid.'.png';
            import('ORG.Util.Image');
            M('user')->where(array('id'=>$this->uid))->data(array('avatar'=>$web_path))->save();
            Image::thumb($source_file, $path.$this->uid.'_small.png', '', 66, 57);
            Image::thumb($source_file, $path.$this->uid.'_middle.png', '', 148, 148);
            Image::thumb($source_file, $path.$this->uid.'_big.png', '', 200, 200);
            exit($info['info']);
        }else{
            $this->assign('WEB_DOMAIN',WEB_DOMAIN);
            $this->display();
        }
    }

    /**
     * 密码修改
     */
    public function password(){
        $this->require_login();
        if($this->isPOST()) {
            $new_pwd = $this->_post('new_pwd');
            $repeat_pwd = $this->_post('repeat_pwd');
            if(empty($new_pwd)){
                $this->error('新密码不能为空');
            }
            if(empty($repeat_pwd)){
                $this->error('重复密码不能为空');
            }

            if(strlen($new_pwd) < 6){
                $this->error('密码不能少于6位数');
            }

            if($new_pwd != $repeat_pwd){
                $this->error('两次输入的密码不一致');
            }
            $user_old_pwd = M('user')->where(array('id'=>$this->uid))->getField('user_pwd');
            $old_pwd = $this->_post('old_pwd');
            if(empty($old_pwd)){
                $this->error('旧密码不能为空');
            }
            if(md5($old_pwd) != $user_old_pwd){
                $this->error('旧密码输入不正确');
            }
            if($old_pwd == $new_pwd){
                $this->error('新密码不能和旧密码相同');
            }
            $status = M('user')->where(array('id'=>$this->uid))->data(array('user_pwd'=>md5($new_pwd)))->save();
            if($status){
                session(null);
                $sync_data = array('email'=>$this->email,'mobile'=>$this->mobile,'password'=>$new_pwd);
                sync_data($sync_data);
                $this->success('密码修改成功,请重新登录','/');
            }else{
                $this->error('密码修改失败');
            }
        }else{
            $this->display();
        }
    }

    /**
     * 添加喜欢的项目
     */
    public function fav_add(){
        if(!$this->get_login_status()){
            exit(json_encode(array('status'=>'-1','info'=>'您没有登陆')));
        }
        $id = $this->_post('id');
        if(!M('deal')->where(array('id'=>$id))->getField('id')){
            exit(json_encode(array('status'=>'0','info'=>'您喜欢的项目不存在')));
        }
        $count = M('deal_fav')->where(array('deal_id'=>$id,'user_id'=>$this->uid))->count();
        if($count > 0){
            //已经关注过
            M('deal')->where(array('id'=>$id))->data(array('focus_count'=>array('exp','focus_count-1')))->save();
            M('deal_fav')->where(array('deal_id'=>$id,'user_id'=>$this->uid))->delete();
            exit(json_encode(array('status'=>'2','info'=>'取消喜欢成功')));
        }
        M('deal')->where(array('id'=>$id))->data(array('focus_count'=>array('exp','focus_count+1')))->save();
        $status = M('deal_fav')->data(array('deal_id'=>$id,'user_id'=>$this->uid))->add();
        if($status){
            exit(json_encode(array('status'=>'1','info'=>'添加喜欢的项目成功')));
        }else{
            exit(json_encode(array('status'=>'0','info'=>'添加喜欢的项目失败')));
        }
    }

    public function support(){
        $this->require_login();
        $condition = array();
        $condition['deal_order.user_id'] = $this->uid;
        $fav_total = M('deal_fav')->where(array('user_id'=>$this->uid))->count();
        $support_total = M('deal_order')->where(array('user_id'=>$this->uid))->count();
        $post_total = M('deal')->where(array('user_id'=>$this->uid))->count();
        $this->assign(array('fav_total'=>intval($fav_total),'support_total'=>intval($support_total),'post_total'=>intval($post_total)));
        $Page = new Page($support_total,10);
        $this->assign('page',$Page->show_front());
        $this->assign("current_page",$Page->nowPage);
        $list = M('deal_order')->alias('deal_order')->join('__DEAL__ deal on deal_order.deal_id = deal.id')->where($condition)->field('deal.*,deal_order.id as order_id,deal_order.deal_item_id,deal_order.pay_time,deal_order.total_price,deal_order.delivery_fee,deal_order.support_memo,deal_order.payment_id,deal_order.bank_id,deal_order.credit_pay,deal_order.online_pay,deal_order.order_status,deal_order.consignee,deal_order.zip,deal_order.mobile,deal_order.province,deal_order.city,deal_order.address,deal_order.is_success,deal_order.repay_time,deal_order.repay_memo,deal_order.is_refund')->limit($Page->firstRow,$Page->listRows)->order('deal_order.id desc')->select();
        foreach($list as $k=>$v)
        {
            $list[$k] = $this->deal_info_format($v);
            $deal_item_images = M('deal_item_image')->where(array('deal_id'=>$v['id']))->find();
            $list[$k]['deal_item_images'] = $deal_item_images['image']?$deal_item_images['image']:"/images/home/default_payback-pic100x100.jpg";
            switch($list[$k]['order_status']){
                case '0':
                    $list[$k]['order_status_text'] = '未支付';
                    break;
                case '1':
                    $list[$k]['order_status_text'] = '过期未支付';
                    break;
                case '2':
                    $list[$k]['order_status_text'] = '限额已满';
                    break;
                case '3':
                    $list[$k]['order_status_text'] = '已支付';
                    break;

            }
        }
//        print_r($list);
        $this->assign('list',$list);
        $this->display();
    }

    /**
     * 绑定手机号接口
     */

    public function bind(){
        if($this->isPost() && $this->isAjax()){
            $username = $this->_post('username');
            $password = $this->_post('password');
            $mobile = $this->_post('mobile');
            $code = $this->_post('code');
            $new_code_valid = session('user_mobile_auth_code_bind');
            $this->check_empty($username,'用户名不能为空');
            $this->check_empty($password,'密码不能为空');
            $this->check_empty($mobile,'绑定的手机号不能为空');
            $this->check_empty($code,'手机验证码不能为空');

            $row = M('user')->where(array('email'=>$username,'user_pwd'=>md5($password)))->limit(1)->find();
            if(!isset($row['id'])){
                $this->return_status('0' , '账号或者密码错误');
            }
            if(!empty($row['mobile'])){
                $this->return_status('0' , '您已经绑定过手机号了，不能重复绑定，如需要修改绑定的手机号，请到用户中心修改');
            }

            if(empty($new_code_valid)){
                $this->return_status( '0' , '请先获取短信验证码');
            }

            if($new_code_valid != $code){
                $this->return_status('0' , '短信验证码不正确');
            }


            $status = M('user')->where(array('email'=>$username,'user_pwd'=>md5($password)))->data(array('mobile'=>$mobile))->save();

            if($status){
                $url = session('redirect_url') ? session('redirect_url') : '/';
                session('uid',$row['id']);
                session('mobile',$row['mobile']);
                session('username',$username);//fix it
                session('email',$row['email']);
                session('avatar',$row['avatar']);
                session('redirect_url',null);
                $result = array('status'=>'1','info'=>'登陆成功','url'=>$url);
                exit(json_encode($result,JSON_HEX_TAG));
            }else{
                $this->return_status('0' , '手机号绑定失败');
            }



        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * 更换手机号接口
     */
    public function protect(){
        $this->require_login();
        if($this->isPost()){
            $old_code_valid = session('user_mobile_auth_code_old');
            $new_code_valid = session('user_mobile_auth_code_new');
            $this->check_empty($old_code_valid,'旧手机短信验证码不存在或者已经失效');
            $this->check_empty($new_code_valid,'新手机短信验证码不存在或者已经失效');
            $o_code = $this->_post('o_code');
            $o_mobile = $this->_post('o_mobile');
            $code = $this->_post('code');
            $mobile = $this->_post('mobile');
            $this->check_empty($o_code,'旧手机验证码不能为空');
            $this->check_empty($o_mobile,'旧手机号码不能为空');
            $this->check_empty($mobile,'新手机号码不能为空');
            $this->check_empty($code,'新手机验证码不能为空');

            if($old_code_valid != $o_code){
                $this->return_status('0','您填写的旧手机验证码不正确');
            }

            if($new_code_valid != $code){
                $this->return_status('0','您填写的新手机验证码不正确');
            }

            if($o_mobile == $mobile){
                $this->return_status('0','新手机号码和旧手机号码不能相同');
            }

            $old_mobile = M('user')->where(array('id'=>$this->uid))->getField('mobile');
            if(empty($old_mobile)){
                $this->return_status('0','您暂时未绑定手机，不能进行修改手机号');
            }
            if($old_mobile != $o_mobile){
                $this->return_status('0','您填写的旧手机号错误');
            }

//            $uid = M('user')->where(array('mobile'=>$mobile))->getField('id');
//            if(!empty($uid) && $uid != $this->uid){
//                $this->return_status('0','您填写的新手机号已被其他账号使用');
//            }

            $status = M('user')->where(array('id'=>$this->uid))->data(array('mobile'=>$mobile))->save();

            if($status){
                $this->return_status('1','手机号更新成功');
            }else{
                $this->return_status('1','手机号更新失败，请联系管理员');
            }
        }else{
            $this->display();
        }
    }


    /**
     * 删除喜欢的项目
     */
    public function fav_del(){
        if(!$this->get_login_status()){
            exit(json_encode(array('status'=>'-1','info'=>'您没有登陆')));
        }
        $id = $this->_post('id');
        if(!M('deal_fav')->where(array('id'=>$id))->getField('id')){
            exit(json_encode(array('status'=>'0','info'=>'您喜欢的项目编号不存在')));
        }
        $status = M('deal_fav')->data(array('id'=>$id,'user_id'=>$this->uid))->delete();
        if($status){
            exit(json_encode(array('status'=>'1','info'=>'删除喜欢的项目成功')));
        }else{
            exit(json_encode(array('status'=>'0','info'=>'删除喜欢的项目失败')));
        }
    }

    /**
     * 收件地址管理
     */
    public function address(){
        $this->require_login();
        if($this->isPOST()){
            $type = strtolower($this->_post('type'));
            $id = $this->_post('id');
            switch($type){
                case 'add'://添加
                    $total = M('user_consignee')->where(array('user_id'=>$this->uid))->count();
                    if($total > 10){
                        exit(json_encode(array('status'=>'0','info'=>'添加的地址不能超过10个,请删除不用的地址再进行添加')));
                    }
                    $data = array();
                    $data['user_id'] = $this->uid;
                    $data['province'] = $this->_post('province');
                    $data['city'] = $this->_post('city');
                    $data['address'] = $this->_post('address');
                    $data['mobile'] = $this->_post('mobile');
                    $data['zip'] = $this->_post('zip');
                    $data['consignee'] = $this->_post('consignee');
                    if($total == 0){
                        $data['default'] = '1';
                    }
                    $status = M('user_consignee')->data($data)->add();
                    if($status){
                        exit(json_encode(array('status'=>'1','info'=>'添加成功')));
                    }else{
                        exit(json_encode(array('status'=>'0','info'=>'添加失败')));
                    }
                    break;
                case 'edit'://编辑
                    $data = array();
                    $data['province'] = $this->_post('province');
                    $data['city'] = $this->_post('city');
                    $data['address'] = $this->_post('address');
                    $data['mobile'] = $this->_post('mobile');
                    $data['zip'] = $this->_post('zip');
                    $data['consignee'] = $this->_post('consignee');
                    $status = M('user_consignee')->where(array('user_id'=>$this->uid,'id'=>$id))->data($data)->save();
                    if($status){
                        exit(json_encode(array('status'=>'1','info'=>'编辑成功')));
                    }else{
                        exit(json_encode(array('status'=>'0','info'=>'编辑失败')));
                    }
                    break;
                case 'del'://删除
                    $status = M('user_consignee')->where(array('user_id'=>$this->uid,'id'=>$id))->delete();
                    $total = M('user_consignee')->where(array('user_id'=>$this->uid))->count();
                    if($total = 1){
                        M('user_consignee')->where(array('user_id'=>$this->uid))->data(array('default'=>'1'))->save();
                    }
                    if($status){
                        exit(json_encode(array('status'=>'1','info'=>'删除成功')));
                    }else{
                        exit(json_encode(array('status'=>'0','info'=>'删除失败')));
                    }
                    break;
                case 'load'://ajax读取指定地址
                    $data = M('user_consignee')->where(array('user_id'=>$this->uid,'id'=>$id))->find();
                    exit(json_encode($data,JSON_HEX_TAG));
                    break;
                case 'def'://设置默认地址
                    M('user_consignee')->where(array('user_id'=>$this->uid))->data(array('default'=>'0'))->save();
                    $status = M('user_consignee')->where(array('user_id'=>$this->uid,'id'=>$id))->data(array('default'=>'1'))->save();
                    if($status){
                        exit(json_encode(array('status'=>'1','info'=>'设置成功')));
                    }else{
                        exit(json_encode(array('status'=>'0','info'=>'设置失败')));
                    }
                    break;
            }
        }else{
            $data = M('user_consignee')->where(array('user_id'=>$this->uid))->limit(10)->select();
            $this->assign('list',$data);
            $this->display();
        }
    }

    /**
     * 找回密码操作
     */
    public function reset_password(){
        $email = strim($_REQUEST['email']);
        if(!check_ipop_limit(get_client_ip(),"user_do_getpassword",5)){
            $this->return_status(0,'提交太快');
        }
        if(!check_email($email))
        {
            $this->return_status(0,'邮箱格式有误');
        }
        elseif(M('user')->where(array('email'=>$email))->count() == 0)
        {
            $this->return_status(0,'邮箱不存在');
        }
        else
        {
            $user_info = M('user')->where(array('email'=>$email))->find();
            $send_id = send_user_password_mail($user_info['id'],$this);
            send_mail($send_id);
            $this->return_status(1,'邮件已经寄出，请查看您的邮箱!');
        }
    }

    /**
     * 验证邮箱
     */
    public function valid(){
        $email = $_REQUEST['account'];
        $code = $_REQUEST['code'];
        $userinfo = M('user')->where(array('email'=>$email))->find();
        if($userinfo){
            M('user')->where(array('email'=>$email))->data(array('code'=>''))->save();
            if($userinfo['code'] == $code){
                session('uid',$userinfo['id']);
                session('mobile',$userinfo['mobile']);
                session('username',$userinfo['user_name']);
                session('email',$userinfo['email']);
                session('avatar',$userinfo['avatar']);
                $this->success('您的账号激活成功,系统正在跳转','/');
            }else{
                send_welcome_mail($userinfo['id'],$userinfo['email'],$userinfo['email']);
                $this->error('您的激活码已经失效,系统已经重新给你发送了激活邮件','/');
            }
        }else{
            $this->error('您的账号信息不存在，请检查您的请求','/');
        }
    }


    /**
     * 重置密码
     */
    public function reset(){
        if($this->isPost()){
            $reset_status = session('reset_password');
            $user_id = session('reset_uid');

            if(empty($reset_status) || empty($user_id)){
                $this->return_status('0' ,'请求异常');
            }

            $code = $this->_post('code');
            if(empty($code)){
                $this->return_status('0' ,'验证码不能为空');
            }else{
                $session_code = session('verify');
                $code = md5(strtoupper($code));
                if(empty($session_code) || $session_code != $code){
                    $this->return_status('0' ,'验证码输入不正确');
                }
            }
            $new_pwd = $this->_post('new_pwd');
            $repeat_pwd = $this->_post('repeat_pwd');
            if(empty($new_pwd)){
                $this->return_status('0' ,'新密码不能为空');
            }
            if(empty($repeat_pwd)){
                $this->return_status('0' ,'重复密码不能为空');
            }

            if(strlen($new_pwd) < 6){
                $this->return_status('0' ,'密码不能少于6位数');
            }

            if($new_pwd != $repeat_pwd){
                $this->return_status('0' ,'两次输入的密码不一致');
            }
            $user_info = M('user')->where(array('id'=>$user_id))->find();
            $status = M('user')->where(array('id'=>$user_id))->data(array('password_verify'=>'','user_pwd'=>md5($new_pwd)))->save();
            session('reset_password',null);
            session('reset_uid',null);
            if($status){
                $sync_data = array('email'=>$user_info['email'],'password'=>$new_pwd);
                sync_data($sync_data);
                $this->return_status('1' ,'密码重置成功,请用新密码登录');
            }else{
                $this->return_status('0' ,'密码重置失败,请联系客服');
            }
        }else{
            if(!empty($_REQUEST['code']))
            {
                $uid = intval($_REQUEST['id']);
                $code = strim($_REQUEST['code']);
                $user_info = M('user')->where(array('id'=>$uid,'password_verify'=>$code))->find();
                if($user_info)
                {
                    if($user_info['is_effect'] == '0'){
                        $this->error('您的账号已被禁用','/');
                    }
                    session('reset_password',1);
                    session('reset_uid',$user_info['id']);
                    M('user')->where(array('id'=>$uid))->data(array('password_verify'=>''))->save();
                    $this->assign('users',$user_info);
                    $this->display();
                }
                else
                {
                    session('reset_password',null);
                    $this->error('您的重置密码链接已经失效,请重新获取','/');
                }
            }else{
                session('reset_password',null);
                $this->error('您的重置密码链接请求无效,请检查您访问的连接','/');
            }
        }
    }


    /**
     * 消息中心
     */
    public function message(){
        $this->require_login();
        $type_list = array('status','comment');
        $type = strtolower($this->_request('type')) == 'status' ? 'status' : 'comment' ;
        $page_size = 10;
        $template = 'message_'.$type;
        if(!in_array($type,$type_list)){
            $this->error('消息类型不正确');
        }

        if($type == 'comment'){
            $total = M('deal_comment')->alias('a')->where(array('a.user_id'=>$this->uid))->count();
            $Page = new Page($total,$page_size);
            $this->assign('page',$Page->show_front());
            $this->assign("current_page",$Page->nowPage);
            $list = M('deal_comment')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->where(array('a.user_id'=>$this->uid))->field('a.*,b.name,b.image')->order('create_time desc')->limit($Page->firstRow,$Page->listRows)->select();
        }else{
            $total = M('deal_news_comment')->alias('a')->where(array('a.user_id'=>$this->uid))->count();
            $Page = new Page($total,$page_size);
            $this->assign('page',$Page->show_front());
            $this->assign("current_page",$Page->nowPage);
            $list = M('deal_news_comment')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->where(array('a.user_id'=>$this->uid))->field('a.*,b.name,b.image')->order('create_time desc')->limit($Page->firstRow,$Page->listRows)->select();
        }
        $this->assign('list',$list);
        $this->display($template);
    }

    /**
     * 查看订单状态
     */
    public function view_order(){
        $this->require_login();
        $id = intval($_REQUEST['id']);
        $data = M('deal_order')->alias('a')->join('__DEAL__ b on a.deal_id = b.id')->join('__DEAL_ITEM__ c on a.deal_item_id = c.id')->field('a.*,b.name as project_name,b.image as project_image,c.title as item_title,c.is_delivery')->where(array('a.user_id|b.user_id'=>$this->uid,'a.id'=>$id))->find();
        if(!$data){
            $this->error('找不到该订单信息');
        }else{
            switch($data['order_status']){
                case '0':
                    $data['order_status_text'] = '未支付';
                    break;
                case '1':
                    $data['order_status_text'] = '过期未支付';
                    break;
                case '2':
                    $data['order_status_text'] = '限额已满';
                    break;
                case '3':
                    $data['order_status_text'] = '已支付';
                    break;

            }
            $this->assign($data);
        }
        $this->display();
    }


    public function upload_identity(){
        $this->require_login();
        if($this->isPOST()){
            $identity_status = M('user')->where(array('id'=>$this->uid))->getField('identity_status');
            if($identity_status == '1'){
                $status  = array('status'=>0,'info'=>'{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "您已经上传过身份证了,不能重新上传"}, "id" : "id"}');
                exit(json_encode($status,JSON_HEX_TAG));
            }
            $path = WEB_PATH.'attachment/identity/';
            $filename = md5($this->uid.$this->email).'.png';
            $web_path = '/attachment/identity/'.$filename;
            $info = webuploader('name',$path,$web_path,$filename);
            M('user')->where(array('id'=>$this->uid))->data(array('identity_status'=>'1'))->save();
            exit($info['info']);
        }
    }


}